﻿using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace HenhouseEnvironmentCtrl
{
    public partial class AddCDKForm : Form
    {
        public AddCDKForm()
        {
            InitializeComponent();
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtCDK.Text))
            {
                MessageBox.Show("CDK不能为空。");
                return;
            }

            using (SqlConnection conn = DBConnection.CreateConnection())
            {
                DBConnection.Open(conn);

                // 检查CDK是否已存在
                SqlCommand checkCmd = new SqlCommand("SELECT COUNT(*) FROM CDK WHERE CDK = @cdk", conn);
                checkCmd.Parameters.AddWithValue("@cdk", txtCDK.Text);
                int count = (int)checkCmd.ExecuteScalar();

                if (count > 0)
                {
                    MessageBox.Show("该CDK已存在，请选择其他CDK。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    DBConnection.Close(conn);
                    return;
                }

                SqlCommand cmd = new SqlCommand("INSERT INTO CDK (CDK, IsAvailable, AvailableUses) VALUES (@cdk, @isAvailable, @availableUses)", conn);
                cmd.Parameters.AddWithValue("@cdk", txtCDK.Text);
                cmd.Parameters.AddWithValue("@isAvailable", chkIsAvailable.Checked);
                cmd.Parameters.AddWithValue("@availableUses", Convert.ToInt32(numAvailableUses.Value));
                cmd.ExecuteNonQuery();
                DBConnection.Close(conn);
            }

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
